---
category: String
created: '2021-06-07'
title: Prepend a line number to each line of a text document
updated: '2021-10-13'
---

**JavaScript version**

```js prependNumbers.js
const prependNumbers = (str) =>
    str
        .split(/\r?\n/)
        .map((line, i) => `${(i + 1).toString().padStart(2, ' ')} ${line}`)
        .join('\n');
```

**TypeScript version**

```ts prependNumbers.ts
const prependNumbers = (str: string): string =>
    str
        .split(/\r?\n/)
        .map((line, i) => `${(i + 1).toString().padStart(2, ' ')} ${line}`)
        .join('\n');
```

**Examples**

```js examples.js
prependNumbers(`one
two
three
four`);

/* Output */
/*
1 one
2 two
3 three
4 four
*/
```
